package com.zkh360.service.message.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.zkh360.service.message.constant.Constants;
import com.zkh360.service.message.constant.ErrorCode;
import com.zkh360.service.message.controller.base.BaseController;
import com.zkh360.service.message.exceptions.BusinessException;
import com.zkh360.service.message.model.BaseResponse;
import com.zkh360.service.message.model.Pager;
import com.zkh360.service.message.model.SysRoleVO;
import com.zkh360.service.message.model.SysUserVO;
import com.zkh360.service.message.model.SysUsersRolesVO;
import com.zkh360.service.message.service.RoleService;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class RoleConrtroller extends BaseController {

	@Autowired
	private RoleService roleService;

	@GetMapping("/roles")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public String roles(Integer currentPage, String userName, String userId, Model model) {
		log.info("获取角色信息");
		Pager pager = new Pager();
		pager.setCurrentPage(currentPage);
		pager.setPageSize(Constants.PAGE_SIZE);

		SysUserVO sysUsers = new SysUserVO();
		sysUsers.setUser_account(userName);
		List<SysRoleVO> sysRoleList = roleService.getRolesByUser(sysUsers, pager);

		// 设置分页信息
		int totalCount = roleService.getRolesCount(sysUsers);
		setPager(currentPage, totalCount, pager);
		model.addAttribute("pager", pager);

		// 前端返回
		model.addAttribute("roles", sysRoleList);
		return "roles";
	}

	/**
	 * 新增角色信息（主要是URL地址）
	 * 
	 * @throws IOException 读写异常
	 */
	@PostMapping("/role/add")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void addRole(@RequestBody SysRoleVO sysRoleVo, HttpServletResponse response) throws IOException {
		log.info("添加角色信息");
		// 前端返回
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "添加成功");
		try {
			roleService.addRole(sysRoleVo);
		} catch (BusinessException e) {
			log.error("添加角色信息异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}

	/**
	 * 删除角色信息
	 * 
	 * @throws IOException IO异常
	 */
	@GetMapping("/role/delete")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void deleteRole(Long roleId, HttpServletResponse response) throws IOException {
		log.info("删除角色信息详情");
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "删除成功");

		try {
			roleService.deleteRole(roleId);
		} catch (BusinessException e) {
			log.error("删除角色信息异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}

	/**
	 * 修改角色信息
	 * 
	 * @throws IOException 读写异常
	 */
	@PostMapping("/role/edit")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void editRole(@RequestBody SysRoleVO sysRoleVo, HttpServletResponse response) throws IOException {
		log.info("修改角色信息");
		// 前端返回
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "添加成功");
		try {
			roleService.editRole(sysRoleVo);
		} catch (BusinessException e) {
			log.error("添加角色信息异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}

	/**
	 * 获取角色信息 主要是点击修改按钮获取详情
	 * 
	 * @throws IOException IO异常
	 */
	@GetMapping("/role")
	public void getRole(Long roleId, HttpServletResponse response) throws IOException {
		log.info("获取角色信息详情");
		SysRoleVO sysRole = new SysRoleVO();
		sysRole.setRole_id(roleId);

		Pager pager = new Pager();
		pager.setCurrentPage(1);
		pager.setPageSize(2);

		List<SysRoleVO> sysRoleList = roleService.getRoles(sysRole, pager);
		BaseResponse<SysRoleVO> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", null);

		if (sysRoleList.size() == 0) {
			result = BaseResponse.fail(ErrorCode.CODE_FAILURE, "查询不到该角色信息！", null);
		} else if (sysRoleList.size() == 1) {
			result.setResult(sysRoleList.get(0));
		} else {
			result = BaseResponse.fail(ErrorCode.CODE_FAILURE, "查询到多个角色信息！", null);
		}

		writeJSON(response, result);
	}

	/**
	 * 获取权限信息 主要是角色点击修改按钮获取权限信息
	 * 
	 * @throws IOException IO异常
	 */
	@GetMapping("/role/user/list")
	public void getRoleByUser(Long userId, HttpServletResponse response) throws IOException {
		log.info("根据用户获取角色信息详情");
		Pager pager = new Pager();
		pager.setCurrentPage(1);
		pager.setPageSize(100);

		List<SysRoleVO> allRoleList = roleService.getRolesByUser(new SysUserVO(), pager);

		SysUserVO sysUsers = new SysUserVO();
		sysUsers.setUser_id(userId);
		List<SysRoleVO> userRoleList = roleService.getRolesByUser(sysUsers, pager);

		Map<Long, String> roleMap = new HashMap<>();
		userRoleList.forEach(sysUser -> {
			roleMap.put(sysUser.getRole_id(), "");
		});

		allRoleList.forEach(sysUser -> {
			if (roleMap.containsKey(sysUser.getRole_id())) {
				sysUser.setIfInuse(true);
			}
		});
		BaseResponse<List<SysRoleVO>> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", allRoleList);
		writeJSON(response, result);
	}

	/**
	 * 修改资源权限信息
	 * 
	 * @throws IOException 读写异常
	 */
	@PostMapping("/role/user/edit")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void ediRoleByUser(@RequestBody List<SysUsersRolesVO> sysUsersRolesVoList, HttpServletResponse response)
			throws IOException {
		log.info("配置用户角色操作");
		// 前端返回
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "添加成功");
		try {
			roleService.ediRoleByUser(sysUsersRolesVoList);
		} catch (BusinessException e) {
			log.error("配置角色权限操作异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}

}
